package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.RmChatShow;
import com.ruoyi.web.cp.domain.rm.RmGame;
import com.ruoyi.web.cp.domain.rm.RmResult;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.mapper.RmChatShowMapper;
import com.ruoyi.web.mapper.RmGameMapper;
import com.ruoyi.web.mapper.RmResultMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RmResultChatShowMergeService {
    @Autowired
    private RmResultMapper rmResultMapper;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private RmGameMapper rmGameMapper;
    @Autowired
    private RmChatShowMapper rmChatShowMapper;
    @Autowired
    private ConfigLoader configLoader;

    @SneakyThrows
    public void merge(Date beginDate, Date endDate) {
        beginDate = DateUtil.offsetHour(new Date(), -24);
        endDate = DateUtil.offsetHour(new Date(), 24);
        List<RmGame> rmGameList = getRmGameList(beginDate, endDate);
        if (CollUtil.isEmpty(rmGameList)) {
            return;
        }
        List<String> gameIds = rmGameList.stream().map(RmGame::getGameId)
                .distinct()
                .collect(Collectors.toList());
        // 生成gameid -> rmGame字典
        Map<String, RmGame> gameIdToRmGameMap = rmGameList.stream().collect(Collectors.toMap(RmGame::getGameId,
                v -> v,
                (existing, replacement) -> existing
        ));

        List<RmResult> rmResultList = getResultsByGameIds(gameIds);
        // 生成 gameId -> allScore 的字典
        Map<String, RmResult> gameIdToAllScoreMap = rmResultList.stream()
                .collect(Collectors.toMap(
                        RmResult::getGameId,
                        v -> v,
                        (existing, replacement) -> existing
                ));

        List<RmChatShow> rmChatShowList = getChatShowByGameIds(gameIds);

        for (RmChatShow item : rmChatShowList) {
            RmResult rmResult = gameIdToAllScoreMap.get(item.getGameId());
            if (rmResult != null) {
                item.getRmResult().setAllScore(rmResult.getAllScore());
                item.getRmResult().setGoalTime(rmResult.getGoalTime());
                item.getRmResult().setHalfScore(rmResult.getHalfScore());
            }

            RmGame rmGame = gameIdToRmGameMap.get(item.getGameId());
            if (rmGame != null) {
                item.getRmResult().setLeague(rmGame.getLeague());
                item.getRmResult().setDate(rmGame.getDate());
                item.getRmResult().setTeamA(rmGame.getTeamA());
                item.getRmResult().setTeamB(rmGame.getTeamB());
            }
        }

        String path = configLoader.getRmPath() + "RM投注量结果.xlsx";
        File tempFile = new File(path);
        // 如果文件已存在，先删除
        if (tempFile.exists()) {
            FileUtil.del(tempFile);
        }
        // 导出到 Excel
        exportRmobDyMergeToExcel(rmChatShowList, tempFile);
        winxinService.uploadMediaByAppAndSendMsg("1000018", path);
    }

    public List<RmGame> getRmGameList(Date beginDate, Date endDate) {
        return rmGameMapper.selectByStartDateAndEndDate(null, beginDate, endDate);
    }

    public List<RmResult> getResultsByGameIds(List<String> gameIds) {
        return rmResultMapper.selectByGameIds(gameIds);
    }

    public List<RmChatShow> getChatShowByGameIds(List<String> gameIds) {
        return rmChatShowMapper.selectByGameIds(gameIds);
    }

    public void exportRmobDyMergeToExcel(List<RmChatShow> rmChatShowList, File tempFile) {
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);

        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队", "首进球时间", "半场结果", "全场结果"};
        writer.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDyMerge 有对应的 getter 方法）
        for (RmChatShow item : rmChatShowList) {
            Date date = item.getRmResult().getDate();

            String dateStr = DateUtil.format(date, "yyyy-MM-dd HH:mm");
            RmResult rmResult = item.getRmResult();
            String goalTime = "", halfScore = "", allScore = "";
            if (rmResult != null) {
                goalTime = rmResult.getGoalTime() == null ? "" : rmResult.getGoalTime();
                halfScore = rmResult.getHalfScore() == null ? "" : rmResult.getHalfScore();
                allScore = rmResult.getAllScore() == null ? "" : rmResult.getAllScore();
            }
            writer.writeRow(Arrays.asList(
                    dateStr,            // 日期
                    item.getRmResult().getLeague(),          // 联赛
                    item.getRmResult().getTeamA(),           // 主队
                    item.getRmResult().getTeamB(),           // 客队
                    goalTime,           // 首进球时间
                    halfScore,          // 半场结果
                    allScore            // 全场结果
            ));

            JSONArray details = item.getDetailsJsonToArray();
            if (CollUtil.isEmpty(details)) {
                continue;
            }

            // 按chat数值倒序排序
            details.sort((o1, o2) -> {
                JSONObject obj1 = (JSONObject) o1;
                JSONObject obj2 = (JSONObject) o2;
                Integer chat1 = Integer.valueOf(obj1.getString("chat"));
                Integer chat2 = Integer.valueOf(obj2.getString("chat"));
                return chat2.compareTo(chat1); // 倒序排列
            });

            for (int i = 0; i < details.size(); i++) {
                JSONObject jsonObject = details.getJSONObject(i);
                //{"chat": "316537", "score": "0-0"}
                writer.writeRow(Arrays.asList(
                        jsonObject.getString("score"),
                        jsonObject.getString("chat")
                ));
            }
        }
        int[] columnWidths = {
                18 * 256, // 日期
                15 * 256, // 联赛
                20 * 256, // 主队
                20 * 256, // 客队
                15 * 256,   // 首进球时间
                8 * 256,   // 半场结果
                8 * 256,  // 全场结果
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
        // 关闭流
        writer.close();
    }

}
